﻿using System.Net.Mail;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;
using System.Collections.ObjectModel;
using System.Windows.Controls.Primitives;
using System.Text.RegularExpressions;

namespace Email_Sending
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            
        }
        private void bottomRightThumb_DragDelta(object sender, DragDeltaEventArgs e)
        {
            Body.Width += e.HorizontalChange;
            Body.Height += e.VerticalChange;
        }

        private void SendEmail_Click(object sender, RoutedEventArgs e)
        {
           
            if (string.IsNullOrEmpty(Sender.Text) || string.IsNullOrEmpty(Receiver.Text))
            {
                MessageBox.Show("缺少邮件地址信息");
                return;
            }
            if (string.IsNullOrEmpty(Title.Text) || string.IsNullOrEmpty(Body.Text))
            {
                MessageBox.Show("缺少邮件内容信息");
                return;
            }
            try
            {
                sendEmail(Title.Text, Body.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发送邮件失败：{ex.Message}");
            }
        }

        private async void sendEmail(string subject, string body)
        {
            string smtpServer = "smtp.qq.com";
            int smtpPort = 587;
            string fromEmail = Sender.Text;  // 发件人QQ邮箱
            string fromPassword = "hicijzfgolqteagd";
            try
            {
                var smtpClient = new SmtpClient(smtpServer)
                {
                    Port = smtpPort,
                    Credentials = new NetworkCredential(fromEmail, fromPassword),
                    EnableSsl = true
                };

                var mailMessage = new MailMessage
                {
                    From = new MailAddress(fromEmail),
                    Subject = subject,
                    Body = body
                };

                //mailMessage.To.Add(Reciever.Text);  // 收件人邮箱
                string[] recipientAddresses = Receiver.Text.Split(';');
                List<string> names = new List<string>();
                await Task.Run(() => 
                {
                    foreach (string address in recipientAddresses)
                    {
                        string trimmedAddress = address.Trim();
                        if (!string.IsNullOrEmpty(trimmedAddress))
                        {
                            string[] information = trimmedAddress.Split(",");
                            if (information.Length == 2)
                            {
                                string rName = information[0].Trim();
                                string rAdress = information[1].Trim();

                                if (!IsValidEmail(rAdress))
                                {
                                    MessageBox.Show($"收件人邮箱地址 {rAdress} 格式不正确");
                                    return;
                                }
                                mailMessage.To.Add(rAdress);
                                names.Add(rName);
                            }
                            else
                            {
                                MessageBox.Show($"收件人信息 {address} 格式不正确，应使用 '姓名,邮箱地址' 格式\n多个收件人以英文分号(;)隔开");
                                return;
                            }
                            //mailMessage.To.Add(trimmedAddress);
                        }
                    }
                    smtpClient.Send(mailMessage);

                    StringBuilder sb = new StringBuilder();
                    foreach (string name in names)
                    {
                        sb.AppendLine(name);
                    }
                    MessageBox.Show($"邮件发送成功!\n收件人:\n{sb}");
                });
                
                
                //MessageBox.Show($"邮件发送成功");
                //Logger.WriteLog($"邮件已发送到{ReceiveEmailAddress},内容为{Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error: {ex.Message}");
                return;
            }
        }
        private bool IsValidEmail(string email)
        {
            // 简单的邮箱格式验证正则表达式
            string pattern = @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$";
            return Regex.IsMatch(email, pattern);
        }
        private void DeleteReceiver_Click(object sender, RoutedEventArgs e)
        {
            string[] recipientAddresses = Receiver.Text.Split(';');
            if (recipientAddresses.Length == 1)
            {
                Receiver.Clear();
            }
            else
            {
                // 移除最后一个邮箱地址
                Array.Resize(ref recipientAddresses, recipientAddresses.Length - 1);

                // 将剩余的邮箱地址用分号重新连接
                string newEmailText = string.Join(";", recipientAddresses);

                // 更新 TextBox 中的文本
                Receiver.Text = newEmailText;
            }
        }

    }
}